//
//  LYAddressPickerView.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/31.
//

import UIKit
import SnapKit

// MARK: - 协议定义
protocol LYAddressPickerDelegate: AnyObject {
    func addressPicker(_ picker: LYAddressPickerView, didSelectItem item: LYDataItem, at level: Int)
    func addressPicker(_ picker: LYAddressPickerView, didCompleteSelection path: [LYDataItem])
    func addressPicker(_ picker: LYAddressPickerView, didClickConfirmButton path: [LYDataItem])
}

extension LYAddressPickerDelegate {
    func addressPicker(_ picker: LYAddressPickerView, didSelectItem item: LYDataItem, at level: Int) {}
    func addressPicker(_ picker: LYAddressPickerView, didCompleteSelection path: [LYDataItem]) {}
    func addressPicker(_ picker: LYAddressPickerView, didClickConfirmButton path: [LYDataItem]) {}
}

// MARK: - 主选择器视图
class LYAddressPickerView: UIView {
    
    // MARK: 配置
    struct Config {
        var provincePlaceholder = ""
        var cityPlaceholder = "  " + LYlocalizedString("Select") + "  "
        var separatorText: String = ""
        var placeholderColor: UIColor = UIColor(hex: "#FFFFFF")
        var selectedColor: UIColor = UIColor(hex: "#000000")
        var selectedBackgroundColor: UIColor = UIColor(hex: "#FFEEC5")
    }
    
    // MARK: 公开属性
    weak var delegate: LYAddressPickerDelegate?
    var config = Config()
    var maxLevel: Int = 3 {
        didSet {
            guard maxLevel >= 2 && maxLevel <= 3 else {
                fatalError("maxLevel must be 2 or 3")
            }
        }
    }
    
    // MARK: 私有属性
    private var dataSource: [LYDataItem] = []
    private var selectedPath: [LYDataItem] = []
    private var currentLevelData: [LYDataItem] = []
    
    // MARK: UI组件
    private lazy var pathScrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceHorizontal = true
        return scrollView
    }()
    
    private lazy var pathStackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.alignment = .fill
        stack.distribution = .fill
        stack.spacing = 4
        return stack
    }()
    
    private lazy var tableView: UITableView = {
        let table = UITableView()
        table.delegate = self
        table.dataSource = self
        table.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        table.tableFooterView = UIView()
        table.backgroundColor = .clear
        table.separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        table.shouldIgnoreScrollingAdjustment = true
        table.shouldRestoreScrollViewContentOffset = true
        return table
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex: "#000000")
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        label.textAlignment = .center
        label.text = LYlocalizedString("Address Selection")
        return label
    }()
    
    lazy var confirmButton: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(confirmButtonAction(_:)), for: .touchUpInside)
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        button.setTitle(LYlocalizedString("Confirm"), for: .normal)
        button.backgroundColor = UIColor(hex: "#1E4FF3")
        button.layer.masksToBounds = true
        button.layer.cornerRadius = (45 * xScale) / 2.0
        return button
    }()
    
    // MARK: 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: 公开方法
    func loadCountryAddress(_ address: CountryAddress) {
        self.dataSource = address.toDataItems()
        resetToFirstLevel()
    }
    
    func resetSelection() {
        resetToFirstLevel()
    }
    
    func getSelectedPath() -> [LYDataItem] {
        return selectedPath
    }
    
    // MARK: 私有方法
    private func setupUI() {
        addSubview(titleLabel)
        addSubview(confirmButton)
        addSubview(pathScrollView)
        pathScrollView.addSubview(pathStackView)
        addSubview(tableView)
        setupConstraints()
    }
    
    private func setupConstraints() {
        
        titleLabel.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(30)
            make.height.equalTo(20)
        }
        
        pathScrollView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(31)
        }
        
        pathStackView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16))
            make.height.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(pathScrollView.snp.bottom).offset(8)
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(confirmButton.snp.top).offset(-20)
        }

        confirmButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(45)
            make.bottom.equalToSuperview().offset(-30)
        }
    }
    
    private func resetToFirstLevel() {
        selectedPath.removeAll()
        currentLevelData = dataSource
        updatePathDisplay()
        tableView.reloadData()
    }
    
    private func updatePathDisplay() {
        // 清除旧视图
        pathStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        
        // 添加所有已选择的路径项
        for (index, item) in selectedPath.enumerated() {
            if index > 0 {
                addSeparator()
            }
            addSelectedPathItem(text: item.name, level: index)
        }
        
        // 如果不是最后一级，添加下一级的占位项
        if selectedPath.count < maxLevel {
            if !selectedPath.isEmpty {
                addSeparator()
            }
            let placeholderText = selectedPath.count == 0 ? config.provincePlaceholder : config.cityPlaceholder
            addPlaceholderItem(text: placeholderText)
        }
        
        // 添加弹性空间
        let spacer = UIView()
        pathStackView.addArrangedSubview(spacer)
        spacer.snp.makeConstraints { make in
            make.width.greaterThanOrEqualTo(0)
        }
        
        // 滚动到最后
        DispatchQueue.main.async {
            let rightOffset = CGPoint(
                x: max(0, self.pathStackView.frame.width - self.pathScrollView.bounds.width + 16),
                y: 0
            )
            self.pathScrollView.setContentOffset(rightOffset, animated: true)
        }
    }
    
    private func addSeparator() {
        let separator = UILabel()
        separator.text = config.separatorText
        separator.font = .systemFont(ofSize: 14)
        separator.textColor = .lightGray
        pathStackView.addArrangedSubview(separator)
    }
    
    private func addSelectedPathItem(text: String, level: Int) {
        let button = UIButton(type: .custom)
        button.setTitle(text, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        button.setTitleColor(config.selectedColor, for: .normal)
        button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 12, bottom: 6, right: 12)
        button.backgroundColor = config.selectedBackgroundColor
        button.layer.cornerRadius = 15.5
        button.tag = level
        button.addTarget(self, action: #selector(pathItemTapped(_:)), for: .touchUpInside)
        pathStackView.addArrangedSubview(button)
    }
    
    private func addPlaceholderItem(text: String) {
        let label = UILabel()
        label.text = text
        label.font = .systemFont(ofSize: 14)
        label.textColor = UIColor(hex: "#FFFFFF")
        label.isUserInteractionEnabled = false
        label.layer.masksToBounds = true
        label.layer.cornerRadius = 15.5
        label.backgroundColor = UIColor(hex: "#FFB606")
        pathStackView.addArrangedSubview(label)
    }
    
    @objc private func pathItemTapped(_ sender: UIButton) {
        navigateToLevel(sender.tag)
    }
    
    private func navigateToLevel(_ level: Int) {
        // 重置到指定层级
        if level < selectedPath.count {
            selectedPath.removeSubrange(level..<selectedPath.count)
        }
        
        // 加载对应层级数据
        if level == 0 {
            currentLevelData = dataSource
        } else if level == 1 {
            currentLevelData = selectedPath[0].children ?? []
        } else if level == 2 {
            currentLevelData = selectedPath[1].children ?? []
        }
        
        updatePathDisplay()
        tableView.reloadData()
        tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
        
        // 通知代理
        if level < selectedPath.count {
            delegate?.addressPicker(self, didSelectItem: selectedPath[level], at: level)
        }
    }
    
    private func selectionComplete() {
        delegate?.addressPicker(self, didCompleteSelection: selectedPath)
    }
    
    @objc func confirmButtonAction(_ sender: UIButton) {
        self.delegate?.addressPicker(self, didClickConfirmButton: selectedPath)
    }
}

// MARK: - UITableView 数据源和代理
extension LYAddressPickerView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return currentLevelData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let item = currentLevelData[indexPath.row]
        
        cell.textLabel?.text = item.name
        cell.textLabel?.font = .systemFont(ofSize: 14)
        cell.textLabel?.textColor = UIColor(hex: "#000000")
        cell.backgroundColor = .clear
        
        if item.isLeaf || (maxLevel == 2 && selectedPath.count == 1) {
            cell.accessoryType = .none
        } else {
            cell.accessoryType = .disclosureIndicator
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let item = currentLevelData[indexPath.row]
        
        // 更新选择路径
        if selectedPath.count > maxLevel - 1 {
            selectedPath.removeSubrange((maxLevel - 1)..<selectedPath.count)
        }
        selectedPath.append(item)
        
        if item.isLeaf || selectedPath.count == maxLevel {
            // 选择完成
            updatePathDisplay()
            selectionComplete()
        } else {
            // 加载下一级数据
            if let children = item.children, !children.isEmpty {
                currentLevelData = children
                updatePathDisplay()
                tableView.reloadData()
                tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
            }
        }
        
        // 通知代理
        delegate?.addressPicker(self, didSelectItem: item, at: selectedPath.count - 1)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48
    }
}
